package week12.producer;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import week12.test.TestActivemq;

import javax.jms.*;
import java.io.IOException;
import java.util.concurrent.atomic.LongAdder;

public class JMSProducer {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String BROKEURL = TestActivemq.BROKEURL;
    private static final int COUNT = 1000;
    public static Connection start(LongAdder adder,int threads) {
        Connection result = null;
        try {
            // 实例化连接工厂
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);
            // 通过连接工厂获取连接
            Connection connection = connectionFactory.createConnection();
            // 启动连接
            connection.start();
            result = connection;
            for (int i = 0; i < threads; i++) {


                new Thread(()->{

                    try {

                        while (true){
                            try {
                                // 获取Session
                                Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
                                // 创建消息队列，queue
                                Destination queueDestination = session.createQueue("week12.topic15");
                                // 创建消息生产者
                                MessageProducer queueProducer = session.createProducer(queueDestination);
                                // 发送消息
                                int count = sendMessage(session, queueProducer);
                                adder.add(count);
                                session.commit();
                                //Thread.sleep(1000);
                            } catch (Exception e) {
                                break;
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();

                    }

                }).start();
            }

        } catch (JMSException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @Description 发送消息
     * @param session
     * @param messageProducer
     * @throws JMSException 
     */
    public static int sendMessage(Session session, MessageProducer messageProducer) throws JMSException {

        for(int i = 0; i < COUNT; i++) {
            TextMessage message = session.createTextMessage("ActiveMQ 发送的消息" + i);
            //System.out.println("ActiveMQ 发送的消息" + i);
            messageProducer.send(message);
        }
        return COUNT;
    }

}
